﻿using DDDSample.Domain.Notifications;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DDDSample.ViewComponents
{
    public class AlertsViewComponent:ViewComponent
    {
        //private IMemoryCache _cache;
        // 领域通知处理程序
        private readonly DomainNotificationHandler _notifications;
        public AlertsViewComponent(DomainNotificationHandler notifications)//IMemoryCache cache)
        {
            //_cache = cache;
            _notifications = notifications;
        }

        /// <summary>
        /// Alert 视图组件
        /// 可以异步，也可以同步，注意方法名称，同步的时候是Invoke
        /// </summary>
        /// <returns></returns>
        public async Task<IViewComponentResult> InvokeAsync()
        {
            //var notificacoes = await Task.Run(()=>(List<string>)ViewBag.ErrorData);
            // 获取缓存中的错误信息
            //var errorData = _cache.Get("ErrorData");
            //var notificacoes = await Task.Run(() => (List<string>)errorData);
            var notificacoes = await Task.FromResult(_notifications.GetNotifications());
            // 遍历错误信息，赋值给 ViewData.ModelState
            notificacoes?.ForEach(c=>ViewData.ModelState.AddModelError(string.Empty,c.Value));

            return View();
        }
    }
}
